package com.example.activiti.service.impl;

import com.example.activiti.common.exclusion.UserDetailsUtil;
import com.example.activiti.common.utils.DateUtils;
import com.example.activiti.common.utils.StringUtils;
import com.example.activiti.common.utils.uuid.UUID;
import com.example.activiti.leave.domain.WorkflowData;
import com.example.activiti.mapper.WorkflowLeaveMapper;
import com.example.activiti.service.IProcessService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 汇讯数码科技(深圳)有限公司
 * 创建日期:2020/10/23-9:52
 * 版本   开发者     日期
 * 1.0    Danny    2020/10/23
 *
 * @author Administrator
 */

@Slf4j
@Service
public class ProcessServiceImpl implements IProcessService {

    @Resource
    private TaskService taskService;
    @Resource
    private ProcessRuntime processRuntime;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private UserDetailsUtil userDetailsUtil;
    @Resource
    private WorkflowLeaveMapper workflowLeaveMapper;


//    @Override
//    public int processStart(WorkflowData workflowData) {
//        String uuid = UUID.randomUUID().toString();
//        String userName = workflowData.getUserId();
//
//        Map<String, Object> param = new HashMap<>(1);
//        param.put("deptLeader", ObjectUtils.isNotEmpty(userName) ? userName : "administrator");
//
//        org.activiti.engine.runtime.ProcessInstance instance = runtimeService.startProcessInstanceByKey(workflowData.getProcessDefinitionKey(), param);
//        log.info("启动流程实例成功:{}", instance);
//        log.info("流程实例ID:{}", instance.getId());
//        log.info("流程定义ID:{}", instance.getProcessDefinitionId());
//
//        // 通过查询正在运行的流程实例来判断
//        ProcessInstanceQuery processInstanceQuery = runtimeService.createProcessInstanceQuery();
//        List<org.activiti.engine.runtime.ProcessInstance> runningList = processInstanceQuery.processInstanceId(instance.getProcessInstanceId()).list();
//        log.info("根据流程ID查询条数:{}", runningList.size());
//
//        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
//        log.info("流程实例ID:{}", instance.getId());
//        log.info("任务名称:{}", task.getName());
//
//        // 启动流程
////        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
////                .start()
////                .withProcessDefinitionKey(workflowData.getProcessDefinitionKey())
////                .withName(workflowData.getTitle())
////                .withBusinessKey(uuid)
////                .build());
//
//        // 保存流程信息
//        workflowData.setId(uuid);
//        workflowData.setCreateTime(DateUtils.getNowDate());
//        workflowData.setInstanceId(instance.getId());
//        workflowData.setState("0");
//        workflowData.setCreateName(userName);
//        workflowData.setCreateBy(userName);
//        workflowData.setCreateTime(DateUtils.getNowDate());
//        return workflowLeaveMapper.insertWorkflowLeave(workflowData);
//    }

    @Override
    public Map<String, String> processStart(WorkflowData workflowData) {
        String businessKey = UUID.randomUUID().toString();
        // 当前用户
        String userId = workflowData.getUserId();
        String userName = workflowData.getUserName();
        userDetailsUtil.loginAs(userId);
        // 根据参数启动流程
        String variableName = workflowData.getVariableName();
        String variableValue = workflowData.getVariableValue();
        ProcessInstance processInstance;
        if (StringUtils.isNotEmpty(variableName) && StringUtils.isNotEmpty(variableValue)) {
            processInstance = processRuntime.start(ProcessPayloadBuilder
                    .start()
                    .withProcessDefinitionKey(workflowData.getProcessDefinitionKey())
                    .withName(workflowData.getTitle())
                    .withBusinessKey(businessKey)
                    .withVariable(variableName, variableValue)
                    .build());
        } else {
            processInstance = processRuntime.start(ProcessPayloadBuilder
                    .start()
                    .withProcessDefinitionKey(workflowData.getProcessDefinitionKey())
                    .withName(workflowData.getTitle())
                    .withBusinessKey(businessKey)
                    .build());
        }
        String processInstanceId = processInstance.getId();
        // 保存流程信息
        workflowData.setId(businessKey);
        workflowData.setCreateTime(DateUtils.getNowDate());
        workflowData.setInstanceId(processInstanceId);
        workflowData.setState("0");
        workflowData.setCreateName(userName);
        workflowData.setCreateBy(userId);
        workflowData.setCreateTime(DateUtils.getNowDate());
        workflowLeaveMapper.insertWorkflowLeave(workflowData);
        // 返回结果
        Map<String, String> processStartDataMap = new HashMap<>(2);
        processStartDataMap.put("businessKey", businessKey);
        processStartDataMap.put("processInstanceId", processInstanceId);
        return processStartDataMap;
    }
}
